#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "wangjing"
# Date: 2018/10/16
# 根据气象规则，获取温馨提示----规则和条件的筛选

import pymssql
import pandas as pd
from datetime import timedelta
import time
import matplotlib.pyplot as plt
from dingtalkchatbot.chatbot import DingtalkChatbot
import math
import numpy as np
import random
from weater_rule import weater_rule


#########运行时间

def fo(fun):
    def md(*args,**kwargs):
        begin_time = time.time()
        reg= fun(*args,**kwargs)  #调用下面的man（）函数
        print('======reg')
        print(time.time()-begin_time)
        return reg
    return md


# ----------------------------读取sql数据---------------------------------------------------

def Obtain_sql(sql_pre, sql_str):
    '''
    :param sql_pre: 数据库语句
    :param sql_str: 把查询的数据转变为datafreme的columns
    :return: 查询数据库，转化为datafrme
    '''
    server = "119.29.146.108"
    user = "sa"
    password = "S3686-e342qq-3686e342"

    connect = pymssql.connect(server, user, password, "istrong_data_collection", charset="utf8")  # 获取连接
    cursor = connect.cursor()  # 获取光标

    cursor.execute(sql_pre)
    number_pre = cursor.fetchall()
    columns = [x for x in sql_str.split(',')]
    weater_data_pre = pd.DataFrame(number_pre, columns=columns)

    connect.close()
    return weater_data_pre


def Insert_sql(sql_pre):
    server = "119.29.146.108"
    user = "sa"
    password = "S3686-e342qq-3686e342"

    connect = pymssql.connect(server, user, password, "istrong_data_collection", charset="utf8")  # 获取连接
    cursor = connect.cursor()  # 获取光标

    cursor.execute(sql_pre)
    connect.commit()
    connect.close()


# ---------------获取气象数据----------------
def weater(day):
    '''
    :param day: 未来day天
    :return: 获取未来day天和前一天的最大温度，最低温度，气温，降水
    '''
    ####----------LJ_FutureWeater--------------未来day天天气
    sql_str_weater = 'STNM,wd_max,wd_min,weater,js_max,c1,c2,YBTM,PSTM'
    sql_pre_weater = "SELECT   {} from {} WHERE PSTM = (select max(PSTM) from {}) ".format(
        sql_str_weater, 'LJ_FutureWeater', 'LJ_FutureWeater')

    weater = Obtain_sql(sql_pre_weater, sql_str_weater)
    now_time = weater['YBTM'].min()
    now_time_n = (now_time + timedelta(days=day - 1)).strftime("%Y-%m-%d")
    weater = weater[weater['YBTM'] <= now_time_n]

    ####--------前1天的数据-------------------
    sql_str_weater_pre = 'STNM,wd_max,wd_min,weater,js_max,c1,c2,YBTM,PSTM'

    now_time_1 = (now_time + timedelta(days=-1)).strftime("%Y-%m-%d")

    sql_pre_weater_pre = "SELECT   {} from {} WHERE PSTM = (select max(PSTM) from {}  WHERE  YBTM= '{}' ) and YBTM= '{}' ".format(
        sql_str_weater_pre, 'LJ_FutureWeater', 'LJ_FutureWeater', now_time_1, now_time_1)

    weater_pre = Obtain_sql(sql_pre_weater_pre, sql_str_weater)

    ##合并-----------------
    weater_data = pd.concat([weater_pre, weater], ignore_index=True)

    return weater_data


############7,15,40区分表达##############################

@fo
def main(day,stnm):
    rqsj = time.strftime('%Y-%m-%d %H:00:00', time.localtime())
    ############1、获取天气数据######################
    weater_data = weater(day)[weater(day)['STNM'] == stnm]  # 获取福州的天气

    ############2、气象规则########################
    weater_data_1,original_data = weater_rule(weater_data, day)

    ############3、初始化参数###############################
    text_sql = ''
    text_dic = {'weater_flu_0_gz': '气温总体平稳', 'weater_flu_1_gz': '温度整体呈下降趋势', 'weater_flu_2_gz': '温度整体呈上升趋势',
                'weater_flu_low_gz': ['可能存在大幅降温','冷空气来袭，大幅降温'], 'weater_flu_up_gz': '有大幅度升温', 'wd_cut_gz': '日均温差较大'}
    fz_dic = {}

    ### 出现次数多，哪个优先
    ###1.优先判断降温升温和日均温差
    weater_data_pd_1 = weater_data_1[['weater_flu_low_gz', 'weater_flu_up_gz']]
    weater_data_1['pd1'] = weater_data_pd_1.idxmax(axis=1)

    ###2.当1的统计结果为0时，判断整体的温度趋势
    weater_data_pd_2 = weater_data_1[['weater_flu_0_gz', 'weater_flu_1_gz', 'weater_flu_2_gz']]
    weater_data_1['pd2'] = weater_data_pd_2.idxmax(axis=1)


    ############共同部分##############################
    for row in weater_data_1.index:

        ###初始化######
        save_text_pr = []
        data = weater_data_1.iloc[row]
        original_data_wt = original_data[original_data['STNM']== data['STNM']]

        original_data_wt['time'] = [x.replace('-','月').replace(':','日') for x in original_data_wt['YBTM'].apply(lambda x: x.strftime("%m{m}%d{d}".format(m='-',d=':'))).tolist()]

        ###########最高温和最低温的范围
        wd_up_max = max(original_data_wt['wd_max'])
        wd_up_min = min(original_data_wt['wd_max'])

        wd_low_max = max(original_data_wt['wd_min'])
        wd_low_min = min(original_data_wt['wd_min'])

        ##############优先级判断写入温馨提示################


        text = '未来{}天，以{}天为主，'.format(day, data['main_weater'],)#我市大致多云间晴，气温小幅波动

        ############7，15，40 分开表达#####################
        if int(day) == 7:
            time_1 = '{}_time'.format(data['pd1'])
            #####################夜间的分析
            if abs(data['lr_xl_min']) >=0.5 :
                if data['lr_xl_min'] < 0:
                    td_min = min(original_data_wt['wd_min'].tolist())
                   # td_time = original_data_wt[original_data_wt['wd_min']==td_min]['YBTM'].tolist()[-1]
                    text+= '夜间整体呈下降趋势，最低温{}℃,'.format(td_min)
                else:
                    text += '夜间整体呈上升趋势，最高温{}℃,'.format(max(original_data_wt['wd_min'].tolist()))

            ####################白天的分析
            elif data['weater_flu_low_gz'] == 0 and data['weater_flu_up_gz'] == 0:
                if abs(data['lr_xl']) <= 0.1:
                    text += '{}'.format(text_dic['weater_flu_0_gz'])
                elif data['lr_xl'] > 0.1:
                    text += '{}'.format(text_dic['weater_flu_2_gz'])
                else:
                    text += '{}'.format(text_dic['weater_flu_1_gz'])

            elif data['pd1'] == 'weater_flu_low_gz':
                data_day = data[time_1].split(',')
                data_max = []
                data_min = []
                for dt in data_day:
                    dt_data = original_data_wt[original_data_wt['time'] == dt]
                    data_min.append(int(max(dt_data['wd_min'])))
                    data_max.append(int(max(dt_data['wd_max'])))
                text += '{},温度较低，最高温在{}℃左右，最低温在{}℃左右'.format(data[time_1],int(sum(data_max)/len(data_max)),int(sum(data_min)/len(data_min)))  # 添加日均温差和降温升温
            else:
                text_dic[weater_data_1['pd2']]

        elif int(day) == 40:
            ###有2次的大幅降温，发生在10月11和10月15日，13天雨天
            wat = original_data_wt['weater'].tolist()
            rain_list = []
            for x in wat:
                if '雨' in x :
                    rain_list.append(x)

            text += '将有{}次的大幅降温，发生在{}'.format(len(data['weater_flu_low_gz_time'].split(',')),data['weater_flu_low_gz_time'])
            if len(rain_list) != 0:
                text += '，将遇到{}天雨天'.format(len(rain_list))
        else:
            # 特殊天气
            if len(data['ts_weater_gz']) > 0:
                text = '将有{}'.format(day, data['main_weater'], data['ts_weater_gz'])

            # 降温和日均差为0
            elif data['weater_flu_low_gz'] == 0 and data['wd_cut_gz'] == 0 and data['weater_flu_up_gz'] == 0:
                if abs(data['lr_xl']) <= 0.1:
                    text += '{}'.format(text_dic['weater_flu_0_gz'])
                elif data['lr_xl']> 0.1:
                    text += '{}'.format(text_dic['weater_flu_2_gz'])
                else:
                    text += '{}'.format(text_dic['weater_flu_1_gz'])
                #text += '{}'.format(text_dic[data['pd2']])
            else:

                time_1 = '{}_time'.format(data['pd1'])
                text += '{},{}'.format(data[time_1], str(random.sample(text_dic[data['pd1']], 1)).replace('[','').replace(']',''))#添加日均温差和降温升温

                if data['pd1'] == 'weater_flu_low_gz':

                    data_day = data[time_1].split(',')
                    for dt in data_day:
                        dt_data = original_data_wt[original_data_wt['time']== dt]
                        text+= '({}气温{}℃~{}℃)'.format(dt,str(max(dt_data['wd_min'])),str(max(dt_data['wd_max'])))

            print()
            # if data['wd_cut_gz'] > int(day / 2):
            #     text += ','
            #     text += str(data['wd_cut_gz_time'])
            #     text += ','
            #     text += str(text_dic['wd_cut_gz'])
            #     text += ',最高温{}-{}℃'.format(str(wd_up_min),str(wd_up_max))
            #     text += ',最低温{}-{}℃'.format(str(wd_low_min),str(wd_low_max))
        ##数据整合
        save_text_pr.append(data['STNM'])
        save_text_pr.append(day)
        save_text_pr.append(text)
        save_text_pr.append(rqsj)
        text_sql += str(tuple(save_text_pr))
        text_sql += ','
        ###########福州的
        fz_dic[data['STNM']] = text

    # 保存到sql格式
    if False:
        insert_sql_str = 'insert into LJ_Tips(code,time,tips,rqsj) values {}'.format(text_sql[:-1])
        Insert_sql(insert_sql_str)
        print('===========完成一次_{}插入'.format(day))

    return fz_dic


def test(stnm):
    days = [7,15,40]
    for day in days:
        data = main(day,stnm)
        print(data[stnm])
       # 钉钉发起post请求
       #  time.sleep(5)
       #  # # WebHook地址
       #  webhook = 'https://oapi.dingtalk.com/robot/send?access_token=c023ebfff1eef6e24393f4f1d82c11a7a589edbcb10b56f4b7bbcf463091a67d'
       #  # 初始化机器人小丁
       #  xiaoding = DingtalkChatbot(webhook)
       #  # Text消息@所有人
       #  xiaoding.send_text(msg=data['101230101'], is_at_all=None)


if __name__ == "__main__":
    ##test########
    stnm = '101230101'
   # test(stnm)

###########正式#########################
    days = [7,15,40]
    while True:
        now_M = time.strftime('%H', time.localtime())
        print('============time')
        print(now_M)
        if now_M == '09' or now_M == '15' or now_M == '19':# now_M == '21' or
            test(stnm)
            print('=============完成一次更新')
        time.sleep(3600)

    #print(reg)


